<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use think\Db;
use think\Request;
use app\common\model\User;
use app\common\model\UserLevel;
use app\common\validate\UserValidate;

require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');
class FafundController extends Controller
{

    /**
     * 用户钱包
     * User:@hang
     */
    public function index(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['a.member_id','=',$param['member_id']];
        }
        if (isset($param['me_uid']) && !empty($param['me_uid'])) {
            $whehe[] = ['a.me_uid','like',"%{$param['me_uid']}%"];
        }
        if (isset($param['me_phone']) && !empty($param['me_phone'])) {
            $whehe[] = ['a.me_phone','like',"%{$param['me_phone']}%"];
        }
        if (isset($param['me_nick_name']) && !empty($param['me_nick_name'])) {
            $whehe[] = ['a.me_nick_name','like',"%{$param['me_nick_name']}%"];
        }
        $IndexTableModel = New IndexTableModel();
        $data = Db::table('fa_member')
            ->alias('a')
            ->join("fa_member_fund b",'a.member_id = b.member_id','LEFT')
            ->where($whehe)
            ->field('a.*,b.*')
            ->order('a.member_id desc')
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);
        $adminid = $this->uid;
        $data->each(function ($v, $k)use($IndexTableModel,$adminid) {
            //只有超管能看全部手机号
            if($adminid != 1){
                $v['me_phone'] = hide_phone_number($v['me_phone']);
            }
            switch($v['me_sex']){
                case '0': $v['me_sex_word'] = '未设置';break;
                case '1': $v['me_sex_word'] = '男';break;
                case '2': $v['me_sex_word'] = '女';break;
            }
//            switch($v['me_standing_type']){
//                case '0': $v['me_sex_word'] .=  '（无身份）';break;
//                case '1': $v['me_sex_word'] .=  '（个人）';break;
//                case '2': $v['me_sex_word'] .=  '（企业）';break;
//            }

            $v['me_status_time_word'] = '-';
            switch($v['me_status']){
                case '1': $v['me_status_word'] = '正常';$v['me_status_time_word'] = '未封禁';break;
                case '2': $v['me_status_word'] = '封禁';
                    if($v['me_status_time'] != -1 && $v['me_status_time'] != 0){
                        $v['me_status_time_word'] = date('Y-m-d H:i:s',$v['me_status_time']);
                    }else{
                        $v['me_status_time_word'] = '永久';
                    }
                    break;
            }

            if(!empty(strpos($v['me_phone'], 'zx'))){
                $v['me_phone'] = explode('zx',$v['me_phone'])[0].'（已注销）';
                $v['me_nick_name'] = explode('zx',$v['me_nick_name'])[0].'（已注销）';
                $v['me_status'] = 99;
                $v['me_status_time_word'] = '已注销';
            }
//            switch($v['me_is_real']){
//                case '0': $v['me_is_real_word'] = '未认证';break;
//                case '1':
//                    if($v['me_status_time_word'] == '已注销'){
//                        $v['me_is_real_word'] = '已注销';
//                    }else{
//                        $v['me_is_real_word'] = '已认证（'.$v['me_realname'].'）';
//                    }
//                    break;
//            }
            $v['me_add_time'] = !empty($v['me_add_time'])?date('m-d H:i:s',$v['me_add_time']):'-';
            $v['me_is_real_word'] = $v['me_is_real'] == 1?'已实名':'未实名';
            $v['me_realname_word'] = !empty($v['me_realname']) && $v['me_is_real'] == 1?$v['me_realname']:'-';
            $v['me_realidcard_word'] = !empty($v['me_realidcard']) && $v['me_is_real'] == 1?$v['me_realidcard']:'-';

            return $v;
        });
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }


    /**
     * 增加/扣除 用户 不可提现油票 页面
     * User:@hang
     */
    public function setnostamp($id)
    {
        //查询用户详情
        $IndexTableModel = New IndexTableModel();
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$id}'",'member_id,me_uid,me_phone,me_nick_name,me_sex,me_realname,me_realidcard,bz_name');
        $this->assign([
            'data' => $id,
            'memberinfo' => $memberInfo,
        ]);
        return $this->fetch();
    }


    /**
     * 确认 增加/扣除 用户 不可提现油票
     * User:@hang
     */
    public function actionsetnostamp()
    {
        $id = input('id');
        $is_type = input('is_type');
        $money = input('money');
        $contents = input('content');
        if(empty($money)){
            return admin_error('请输入油票数',URL_CLOSE_REFRESH);
        }
        if(!is_numeric($money) || $money <= 0){
            return admin_error('请输入正确的油票数',URL_CLOSE_REFRESH);
        }
        $content = '';
        if(!empty($contents)){
            $content = "【理由：{$contents}】";
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionsetnostamp'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        Db::startTrans();
        $IndexTableModel = New IndexTableModel();
        $memberFundInfo = $IndexTableModel->getFind('fa_member_fund',"`member_id` = '{$id}'",'member_id,sex,no_stamp_money');
//        if($memberFundInfo['sex'] != 2){
//            Db::rollback(); // 回滚事务
//            $Redis_Lock->unlock($otc_sell_key);	//释放锁
//            return admin_error('只能给女性用户操作',URL_CLOSE_REFRESH);
//        }
        if($is_type == 1){
            $financeType = 39;$financeStatus = 1;$financeContent = '平台增加油票';$logContent= '增加不可提现油票'.$money;
            //增加
            $newMoney = delete0(bcadd($memberFundInfo['no_stamp_money'],$money,4));
        }else{
            //减少
            if($memberFundInfo['no_stamp_money'] < $money){
                Db::rollback(); // 回滚事务
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('扣除油票数超出用户目前油票数',URL_CLOSE_REFRESH);
            }
            $financeType = 40;$financeStatus = 2;$financeContent = '平台扣除油票';$logContent= '扣除不可提现油票'.$money;
            $newMoney = delete0(bcsub($memberFundInfo['no_stamp_money'],$money,4));
        }
        //操作用户钱包
        $IndexTableModel->editInfo('fa_member_fund',"`member_id` = '{$id}'",['no_stamp_money'=>$newMoney]);
        //增加财务日志
        $Common = New Common();
        $finRes = $Common->setFinance($id,'','',0,$financeType,1,$financeStatus,$money,$financeContent.$content,0);
        if($finRes['code'] != 200){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('增加财务日志失败',URL_CLOSE_REFRESH);
        }
        //增加操作日志
        $data = array();
        $data['user_id'] = $this->uid;
        $data['type'] = 8;
        $data['member_id'] = $id;
        $data['d_member_id'] = 0;
        $data['content'] = '为【'.$id.'】用户'.$logContent.$content;
        $data['add_time'] = time();
        $logRes = $IndexTableModel->addInfo('fa_user_operate_log',$data);
        if(empty($logRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('管理端操作日志添加失败',URL_CLOSE_REFRESH);
        }
        Db::commit(); // 提交事务
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('操作成功',URL_CLOSE_REFRESH);
    }




    /**
     * 增加/扣除 用户 可提现油票 页面
     * User:@hang
     */
    public function setstamp($id)
    {
        //查询用户详情
        $IndexTableModel = New IndexTableModel();
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$id}'",'member_id,me_uid,me_phone,me_nick_name,me_sex,me_realname,me_realidcard,bz_name');
        $this->assign([
            'data' => $id,
            'memberinfo' => $memberInfo,
        ]);
        return $this->fetch();
    }


    /**
     * 确认 增加/扣除 用户 可提现油票
     * User:@hang
     */
    public function actionsetntamp()
    {
        $id = input('id');
        $is_type = input('is_type');
        $money = input('money');
        $contents = input('content');
        if(empty($money)){
            return admin_error('请输入油票数',URL_CLOSE_REFRESH);
        }
        if(!is_numeric($money) || $money <= 0){
            return admin_error('请输入正确的油票数',URL_CLOSE_REFRESH);
        }
        $content = '';
        if(!empty($contents)){
            $content = "【理由：{$contents}】";
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionsetntamp'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        Db::startTrans();
        $IndexTableModel = New IndexTableModel();
        $memberFundInfo = $IndexTableModel->getFind('fa_member_fund',"`member_id` = '{$id}'",'member_id,sex,stamp_money');
        if($memberFundInfo['sex'] != 2){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('只能给女性用户操作',URL_CLOSE_REFRESH);
        }
        if($is_type == 1){
            $financeType = 39;$financeStatus = 1;$financeContent = '平台增加油票';$logContent= '增加可提现油票'.$money;
            //增加
            $newMoney = delete0(bcadd($memberFundInfo['stamp_money'],$money,4));
        }else{
            //减少
            if($memberFundInfo['stamp_money'] < $money){
                Db::rollback(); // 回滚事务
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('扣除油票数超出用户目前油票数',URL_CLOSE_REFRESH);
            }
            $financeType = 40;$financeStatus = 2;$financeContent = '平台扣除油票';$logContent= '扣除可提现油票'.$money;
            $newMoney = delete0(bcsub($memberFundInfo['stamp_money'],$money,4));
        }
        //操作用户钱包
        $IndexTableModel->editInfo('fa_member_fund',"`member_id` = '{$id}'",['stamp_money'=>$newMoney]);
        //增加财务日志
        $Common = New Common();
        $finRes = $Common->setFinance($id,'','',0,$financeType,2,$financeStatus,$money,$financeContent.$content,0);
        if($finRes['code'] != 200){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('增加财务日志失败',URL_CLOSE_REFRESH);
        }
        //增加操作日志
        $data = array();
        $data['user_id'] = $this->uid;
        $data['type'] = 9;
        $data['member_id'] = $id;
        $data['d_member_id'] = 0;
        $data['content'] = '为【'.$id.'】用户'.$logContent.$content;
        $data['add_time'] = time();
        $logRes = $IndexTableModel->addInfo('fa_user_operate_log',$data);
        if(empty($logRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('管理端操作日志添加失败',URL_CLOSE_REFRESH);
        }
        Db::commit(); // 提交事务
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('操作成功',URL_CLOSE_REFRESH);
    }


    /**
     * 取消用户实名 页面
     * User:@hang
     */
    public function qxrealname($id)
    {
        //查询用户详情
        $IndexTableModel = New IndexTableModel();
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$id}'",'*');
        $this->assign([
            'data' => $id,
            'memberinfo' => $memberInfo,
        ]);
        return $this->fetch();
    }


    /**
     * 确认 取消用户实名
     * User:@hang
     */
    public function actionqxrealname()
    {
        $id = input('id');
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionqxrealname'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        Db::startTrans();
        $IndexTableModel = New IndexTableModel();

        $IndexTableModel->editInfo('fa_member',"`member_id` = '{$id}'",['me_is_real'=>0,'me_realname'=>'','me_realidcard'=>'','me_yzh'=>0]);
        $IndexTableModel->delOne('fa_member_trueimg',"`member_id` = '{$id}'");

        Db::commit(); // 提交事务
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('取消用户实名成功',URL_CLOSE_REFRESH);
    }





    /**
     * 后台操作日志
     * User:@hang
     */
    public function getadminlog(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['username']) && !empty($param['username'])) {
            $whehe[] = ['b.username','=',$param['username']];
        }
        if (isset($param['type']) && !empty($param['type'])) {
            $whehe[] = ['a.type','=',$param['type']];
        }
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['a.member_id','=',$param['member_id']];
        }
        $data = Db::table('fa_user_operate_log')
            ->alias('a')
            ->join("admin_user b",'a.user_id = b.id','LEFT')
            ->join("fa_member c",'a.member_id = c.member_id','LEFT')
            ->where($whehe)
            ->field('a.*,b.username,b.nickname')
            ->order('a.add_time desc')
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);
        $getoperatetype = $this->getoperatetype();
        $data->each(function ($v, $k)use($getoperatetype){
            $v['type_word'] = $getoperatetype[$v['type']];
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            return $v;
        });
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
            'getoperatetype' => $getoperatetype,
        ]);
        return $this->fetch();
    }


    /**
     * 后台操作日志类型
     * User:@hang
     */
    public function getoperatetype()
    {
        $data = [1=>'封禁账号',2=>'解封账号',3=>'绑定下级',4=>'解绑下级',5=>'绑定上级',6=>'打开VIP',7=>'关闭VIP',8=>'操作【不可提现油票】',9=>'操作【可提现油票】',10=>'强制注销'];
        return $data;
    }




}
